package bc.swim2.web.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import bc.swim2.ejb.entity.Ability;
import bc.swim2.ejb.entity.AbilityRequest;
import bc.swim2.ejb.entity.Feedback;
import bc.swim2.ejb.entity.Friendship;
import bc.swim2.ejb.entity.RegisteredUser;
import bc.swim2.ejb.session.AbilityManagerBeanRemote;
import bc.swim2.ejb.session.AbilityRequestManagerBeanRemote;
import bc.swim2.ejb.session.FeedbackManagerBeanRemote;
import bc.swim2.ejb.session.FriendshipManagerBeanRemote;
import bc.swim2.ejb.session.UserManagerBeanRemote;

/**
 * Servlet implementation class MainServlet
 */
public class MainServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public MainServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		if (request.getParameter("to").equals("NotRegSearchHelp")) {
			toNotRegSearchHelp(request, response);
			return;
		} else if (request.getParameter("to").equals("NotRegSearchHelpResult")) {
			toNotRegSearchHelpResult(request, response);
			return;
		} else if (request.getParameter("to").equals("Index")) {
			toIndex(request, response);
			return;
		}

		HttpSession session = request.getSession(true);
		Object o = session.getAttribute("currentSessionUser");
		if (o == null) {
			toIndex(request, response);
			return;
		}

		if (request.getParameter("to").equals("RegisteredUserHome")) {
			toRegisteredUserHome(request, response);
		} else if (request.getParameter("to").equals("AdminHome")) {
			toAdminHome(request, response);
		} else if (request.getParameter("to").equals("ShowAbilityRequests")) {
			toShowAbilityRequests(request, response);
		} else if (request.getParameter("to").equals("SearchHelp")) {
			toSearchHelp(request, response);
		} else if (request.getParameter("to").equals("SearchUsers")) {
			toSearchUsers(request, response);
		} else if (request.getParameter("to").equals("AbilityRequest")) {
			toAbilityRequest(request, response);
		} else if (request.getParameter("to")
				.equals("SearchHelpAndUsersResult")) {
			toSearchHelpAndUsersResult(request, response);
		} else if (request.getParameter("to").equals("FriendshipRequests")) {
			toFriendshipRequests(request, response);
		} else if (request.getParameter("to").equals("Friends")) {
			toFriends(request, response);
		} else if (request.getParameter("to").equals("MyFeedback")) {
			toMyFeedback(request, response);
		} else if (request.getParameter("to").equals("MyAbilities")) {
			toMyAbilities(request, response);
		} else if (request.getParameter("to").equals("Profile")) {
			toProfile(request, response);
		} else if (request.getParameter("to").equals("WriteFeedback")) {
			toWriteFeedback(request, response);
		} else if (request.getParameter("to").equals("ProfileFeedback")) {
			toProfileFeedback(request, response);
		} else if (request.getParameter("to").equals("FriendsOfFriends")) {
			toFriendsOfFriends(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		if (request.getParameter("to").equals("AdminHome")) {
			toAdminHome(request, response);
		}
	}

	private void toRegisteredUserHome(HttpServletRequest request,
			HttpServletResponse response) {

		try {
			HttpSession session = request.getSession(true);
			Context ctx = (Context) session.getAttribute("ctx");
			Object ref4 = ctx.lookup("AbilityManagerBean/remote");
			AbilityManagerBeanRemote am = (AbilityManagerBeanRemote) ref4;

			Object ref5 = ctx.lookup("FriendshipManagerBean/remote");
			FriendshipManagerBeanRemote fm = (FriendshipManagerBeanRemote) ref5;

			RegisteredUser user = (RegisteredUser) session
					.getAttribute("currentSessionUser");
			List<Ability> abilities = null;
			List<RegisteredUser> fnv = null;

			abilities = am.getUserAbility(user);
			request.setAttribute("abilityList", abilities);

			fnv = fm.getFrndshpNotVisualized(user);
			request.setAttribute("friendsNotVisualized", fnv);

			Map<Integer, Boolean> fnvMap = new HashMap<Integer, Boolean>();
			int uid;

			for (RegisteredUser u : fnv) {
				uid = u.getId();
				Friendship fr = fm.getFriendship(user, u);
				fnvMap.put(uid, fr.getIndirect());
			}

			request.setAttribute("indirectMap", fnvMap);

			request.getRequestDispatcher("RegisteredUserHome.jsp").forward(
					request, response);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void toNotRegSearchHelp(HttpServletRequest request,
			HttpServletResponse response) {

		try {
			HttpSession session = request.getSession(true);
			Context ctx = new InitialContext();
			session.setAttribute("ctx", ctx);

			List<Ability> allAbilities = null;

			Object ref3 = ctx.lookup("AbilityManagerBean/remote");
			AbilityManagerBeanRemote am = (AbilityManagerBeanRemote) ref3;

			allAbilities = am.getAbilityList();

			request.setAttribute("allAbilityList", allAbilities);
			request.getRequestDispatcher("NotRegisteredSearchHelp.jsp")
					.forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unchecked")
	private void toNotRegSearchHelpResult(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			HttpSession session = request.getSession(true);

			List<RegisteredUser> users = (List<RegisteredUser>) session
					.getAttribute("userListTmp2");
			request.setAttribute("userList", users);

			request.getRequestDispatcher("NotRegSearchHelpResult.jsp").forward(
					request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void toAdminHome(HttpServletRequest request,
			HttpServletResponse response) {

		try {
			HttpSession session = request.getSession(true);
			Context ctx = (Context) session.getAttribute("ctx");
			List<Ability> abilities;
			Object ref3;
			ref3 = ctx.lookup("AbilityManagerBean/remote");
			AbilityManagerBeanRemote abilityManager = (AbilityManagerBeanRemote) ref3;
			abilities = abilityManager.getAbilityList();
			request.setAttribute("allAbilityList", abilities);
			request.getRequestDispatcher("AdminHome.jsp").forward(request,
					response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void toShowAbilityRequests(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			HttpSession session = request.getSession(true);
			Context ctx = (Context) session.getAttribute("ctx");

			Object ref2 = ctx.lookup("AbilityRequestManagerBean/remote");
			AbilityRequestManagerBeanRemote am = (AbilityRequestManagerBeanRemote) ref2;

			List<AbilityRequest> abilityRequests;
			abilityRequests = am.getAbilityRequestList();
			request.setAttribute("abilityRequestList", abilityRequests);

			request.getRequestDispatcher("ShowAbilityRequests.jsp").forward(
					request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void toSearchHelp(HttpServletRequest request,
			HttpServletResponse response) {

		try {
			HttpSession session = request.getSession(true);
			Context ctx = (Context) session.getAttribute("ctx");
			Object ref3 = ctx.lookup("AbilityManagerBean/remote");
			AbilityManagerBeanRemote am = (AbilityManagerBeanRemote) ref3;

			List<Ability> allAbilities = am.getAbilityList();

			request.setAttribute("allAbilityList", allAbilities);
			request.getRequestDispatcher("SearchHelp.jsp").forward(request,
					response);
		} catch (Exception e) {
			e.printStackTrace();

		}
	}

	private void toSearchUsers(HttpServletRequest request,
			HttpServletResponse response) {

		try {
			request.getRequestDispatcher("SearchUsers.jsp").forward(request,
					response);
		} catch (Exception e) {
			e.printStackTrace();

		}
	}

	private void toAbilityRequest(HttpServletRequest request,
			HttpServletResponse response) {

		try {
			request.getRequestDispatcher("AbilityRequest.jsp").forward(request,
					response);
		} catch (Exception e) {
			e.printStackTrace();

		}
	}

	@SuppressWarnings("unchecked")
	private void toSearchHelpAndUsersResult(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			HttpSession session = request.getSession(true);
			Context ctx = (Context) session.getAttribute("ctx");
			Object ref = ctx.lookup("FriendshipManagerBean/remote");
			FriendshipManagerBeanRemote fm = (FriendshipManagerBeanRemote) ref;

			List<RegisteredUser> tmpUsers = (List<RegisteredUser>) session
					.getAttribute("userListTmp1");

			List<RegisteredUser> users = new ArrayList<RegisteredUser>();

			RegisteredUser me = (RegisteredUser) session
					.getAttribute("currentSessionUser");

			for (RegisteredUser ru : tmpUsers) {
				if (ru.getId() != me.getId()) {
					users.add(ru);
				}
			}

			Map<Integer, String> frMap = new HashMap<Integer, String>();
			int uid;
			int cuid = me.getId();

			for (RegisteredUser u : users) {
				uid = u.getId();
				String fs = fm.getFriendshipState(cuid, uid);
				frMap.put(uid, fs);
			}

			request.setAttribute("userList", users);
			request.setAttribute("frMap", frMap);
			request.getRequestDispatcher("SearchHelpAndUsersResult.jsp")
					.forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void toFriendshipRequests(HttpServletRequest request,
			HttpServletResponse response) {

		try {
			HttpSession session = request.getSession(true);
			Context ctx = (Context) session.getAttribute("ctx");

			Object ref3 = ctx.lookup("FriendshipManagerBean/remote");
			FriendshipManagerBeanRemote fm = (FriendshipManagerBeanRemote) ref3;

			RegisteredUser ru = (RegisteredUser) session
					.getAttribute("currentSessionUser");
			List<RegisteredUser> usrs = fm.getFriendshipRequestList(ru);

			request.setAttribute("frndshprqstusrsList", usrs);
			request.getRequestDispatcher("FriendshipRequests.jsp").forward(
					request, response);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void toFriendsOfFriends(HttpServletRequest request,
			HttpServletResponse response) {

		try {
			HttpSession session = request.getSession(true);
			Context ctx = (Context) session.getAttribute("ctx");

			Object ref3 = ctx.lookup("UserManagerBean/remote");
			UserManagerBeanRemote um = (UserManagerBeanRemote) ref3;

			Object ref4 = ctx.lookup("FriendshipManagerBean/remote");
			FriendshipManagerBeanRemote fm = (FriendshipManagerBeanRemote) ref4;

			RegisteredUser ru = um.getUserById((Integer) session
					.getAttribute("accFrIdTmp"));
			RegisteredUser currentUser = ((RegisteredUser) session
					.getAttribute("currentSessionUser"));
			int cuid = currentUser.getId();

			List<RegisteredUser> users = fm.getFriendList(ru);
		
			Map<Integer, String> frOfFrMap = new HashMap<Integer, String>();
			int uid;
			
			for (RegisteredUser u : users) {
				uid = u.getId();
				String fs = fm.getFriendshipState(cuid, uid);
				frOfFrMap.put(uid, fs);
			}

			request.setAttribute("friendsOfFriends", users);
			request.setAttribute("frOfFrMap", frOfFrMap);
			request.getRequestDispatcher("FriendsOfFriends.jsp").forward(
					request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void toFriends(HttpServletRequest request,
			HttpServletResponse response) {

		try {
			HttpSession session = request.getSession(true);
			Context ctx = (Context) session.getAttribute("ctx");

			Object ref3 = ctx.lookup("FriendshipManagerBean/remote");
			FriendshipManagerBeanRemote fm = (FriendshipManagerBeanRemote) ref3;

			RegisteredUser ru = (RegisteredUser) session
					.getAttribute("currentSessionUser");

			List<RegisteredUser> usrs = fm.getFriendList(ru);

			request.setAttribute("friendList", usrs);
			request.getRequestDispatcher("Friends.jsp").forward(request,
					response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void toMyFeedback(HttpServletRequest request,
			HttpServletResponse response) {

		try {
			List<RegisteredUser> user = new ArrayList<RegisteredUser>();
			List<Feedback> feedbackList = null;
			List<Ability> ability = new ArrayList<Ability>();

			HttpSession session = request.getSession(true);
			Context ctx = (Context) session.getAttribute("ctx");

			Object ref2 = ctx.lookup("FeedbackManagerBean/remote");
			FeedbackManagerBeanRemote fm = (FeedbackManagerBeanRemote) ref2;

			Object ref3 = ctx.lookup("UserManagerBean/remote");
			UserManagerBeanRemote um = (UserManagerBeanRemote) ref3;

			Object ref4 = ctx.lookup("AbilityManagerBean/remote");
			AbilityManagerBeanRemote am = (AbilityManagerBeanRemote) ref4;

			RegisteredUser currentUser = (RegisteredUser) session
					.getAttribute("currentSessionUser");

			feedbackList = fm.getFeedbackByReceiverId(currentUser.getId());
			for (Feedback f : feedbackList) {
				user.add(um.getUserById(f.getSenderId()));
				if (am.getAbilityById(f.getAbilityId()) == null)
					ability.add(new Ability(0, "Ability removed"));
				else
					ability.add(am.getAbilityById(f.getAbilityId()));

			}
			request.setAttribute("feedbackList", feedbackList);
			request.setAttribute("senderUsers", user);
			request.setAttribute("ability", ability);
			request.setAttribute("me", "yes");
			request.getRequestDispatcher("MyFeedback.jsp").forward(request,
					response);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void toMyAbilities(HttpServletRequest request,
			HttpServletResponse response) {

		try {
			HttpSession session = request.getSession(true);
			Context ctx = (Context) session.getAttribute("ctx");

			List<Ability> myAbilities = null;
			List<Ability> allAbilities = null;
			List<Ability> remainingAbilities = new ArrayList<Ability>();
			RegisteredUser ru = null;

			Object ref3 = ctx.lookup("AbilityManagerBean/remote");
			AbilityManagerBeanRemote am = (AbilityManagerBeanRemote) ref3;

			ru = (RegisteredUser) session.getAttribute("currentSessionUser");

			myAbilities = am.getUserAbility(ru);

			allAbilities = am.getAbilityList();

			for (Ability a : allAbilities) {
				if (!myAbilities.contains(a))
					remainingAbilities.add(a);
			}

			request.setAttribute("abilityList", myAbilities);
			request.setAttribute("remainingAbilityList", remainingAbilities);
			request.getRequestDispatcher("MyAbilities.jsp").forward(request,
					response);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void toProfile(HttpServletRequest request,
			HttpServletResponse response) {

		List<Ability> abilities = null;
		String userIdString;
		int userId;

		try {
			HttpSession session = request.getSession(true);
			Context ctx = (Context) session.getAttribute("ctx");

			Object ref3 = ctx.lookup("UserManagerBean/remote");
			UserManagerBeanRemote um = (UserManagerBeanRemote) ref3;

			Object ref4 = ctx.lookup("AbilityManagerBean/remote");
			AbilityManagerBeanRemote am = (AbilityManagerBeanRemote) ref4;

			RegisteredUser user = (RegisteredUser) session
					.getAttribute("profileUser");

			if (user == null) {
				userIdString = request.getParameter("userId");
				userId = Integer.parseInt(userIdString);

				user = um.getUserById(userId);
				session.setAttribute("profileUser", user);
			}

			abilities = am.getUserAbility(user);
			request.setAttribute("profileAbilityList", abilities);

			request.getRequestDispatcher("Profile.jsp").forward(request,
					response);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void toWriteFeedback(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			HttpSession session = request.getSession(true);
			Context ctx = (Context) session.getAttribute("ctx");

			Object ref4 = ctx.lookup("AbilityManagerBean/remote");
			AbilityManagerBeanRemote am = (AbilityManagerBeanRemote) ref4;

			RegisteredUser profileUser = (RegisteredUser) session
					.getAttribute("profileUser");
			List<Ability> profileUserAbilities = am.getUserAbility(profileUser);

			request.setAttribute("profileUserAbilities", profileUserAbilities);
			request.getRequestDispatcher("WriteFeedback.jsp").forward(request,
					response);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void toProfileFeedback(HttpServletRequest request,
			HttpServletResponse response) {

		try {
			HttpSession session = request.getSession(true);
			Context ctx = (Context) session.getAttribute("ctx");

			Object ref3 = ctx.lookup("UserManagerBean/remote");
			UserManagerBeanRemote um = (UserManagerBeanRemote) ref3;

			Object ref2 = ctx.lookup("FeedbackManagerBean/remote");
			FeedbackManagerBeanRemote fm = (FeedbackManagerBeanRemote) ref2;

			List<RegisteredUser> users = new ArrayList<RegisteredUser>();
			RegisteredUser ru = (RegisteredUser) session
					.getAttribute("profileUser");
			List<Feedback> feedbacks = fm.getFeedbackByReceiverId(ru.getId());
			List<Ability> abilities = new ArrayList<Ability>();

			Object ref4 = ctx.lookup("AbilityManagerBean/remote");
			AbilityManagerBeanRemote am = (AbilityManagerBeanRemote) ref4;

			for (Feedback f : feedbacks) {
				users.add(um.getUserById(f.getSenderId()));
				if (am.getAbilityById(f.getAbilityId()) == null)
					abilities.add(new Ability(0, "Ability removed"));
				else
					abilities.add(am.getAbilityById(f.getAbilityId()));

			}
			request.setAttribute("feedbackList", feedbacks);
			request.setAttribute("senderUsers", users);
			request.setAttribute("ability", abilities);
			request.setAttribute("me", "no");
			request.getRequestDispatcher("MyFeedback.jsp").forward(request,
					response);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void toIndex(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			request.getRequestDispatcher("index.jsp")
					.forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
